package com.xls.commonlibrary.http;

import android.app.ProgressDialog;
import android.content.Context;

import com.orhanobut.logger.Logger;

import java.lang.ref.SoftReference;

import io.reactivex.rxjava3.annotations.NonNull;
import io.reactivex.rxjava3.core.Observer;
import io.reactivex.rxjava3.disposables.Disposable;

// 封装进度弹框
// observable事件开始，Observer观察到开始，打开PD
// observable事件结束，Observer观察到关闭，关闭PD
// observable事件-----Observer观察回调一一对应，


// fixme 内存泄露
// todo mActivity 需要处理生命周期，注销的问题，


// todo 错误预处理，json格式错误的处理，网络错误的处理，

public class DialogObserver<T> implements Observer<T> {


    private SoftReference<Context> mActivity;
    private SoftReference<Callback> mCallback;//Observer数据hook回调给页面，但是不符合rx的链式调用了


    private ProgressDialog pd;

    private void initPd() {

        if (pd == null) {
            Context context = mActivity.get();
            pd = new ProgressDialog(context);
        }

        Logger.d(" pd.show();=======");
        pd.show();
    }

    private void dismissProgressDialog() {
        Logger.d(" pd.dismiss();=======");
        if (pd != null) {
            pd.dismiss();
        }
    }

    public DialogObserver(SoftReference<Context> mActivity) {
        this.mActivity = mActivity;
    }

    public DialogObserver(SoftReference<Context> mActivity, SoftReference<Callback> mCallback) {
        this.mActivity = mActivity;
        this.mCallback = mCallback;
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        Logger.d("onSubscribe=======");
        initPd();
    }

    @Override
    public void onNext(T t) {

        Logger.d("onNext=======" + t);
        // todo 解析数据，解析错误需要回调错误
        if (mCallback != null && mCallback.get() != null) mCallback.get().onNext();
    }

    @Override
    public void onError(Throwable t) {

        Logger.d("onError=======");
        // todo 错误预处理后，返回错误
        if (mCallback != null && mCallback.get() != null) mCallback.get().onError();
        dismissProgressDialog();



    }

    @Override
    public void onComplete() {

        Logger.d("onComplete=======");
        dismissProgressDialog();

        if (mCallback != null && mCallback.get() != null) mCallback.get().complete();
    }
}
